Automatic Reporting with rmarkdown

Carlos Bort & Lluís Ramon

Thursday, February 26, 2015

Motivación

Automatizar

Reproducible

Diferentes formatos

Ejemplo

  1. Data preparation
  2. Modeling
  3. Generating report
  4. Something wrong in your data
  5. Repeat 1 ~ 4



Slide copiada de Mansun Kuo

Conceptos

Requisitos

Versiones de R y RStudio actualitzadas:

Los siguientes packages de R:

Una distribución de TeX

Ejercicio 1: Generar el primer documento

output_option output_option

Markdown basics

# Nivel 1
## Nivel 2
### Nivel 3

*cursiva*   **negrita**
_cursiva_   __negrita__

[link](https://rugbcn.wordpress.com/)

* lista de elementos
* elemento 2
 + elemento 2.1
 + elemento 2.2
* elemento 3

Formulas en formato LaTeX $\beta^2$

<!-- Comentario en Markdown basics -->

output_option output_option

Document Templates

Foo2

Ejercicio 2: Customizar el documento

Opciones de las templates

Foo3

Corrector ortográfico

output_option output_option

Knitr

Que és?

Que és un chunk?

paste("Mi primer chunk, empecemos por un simple paste!")
## [1] "Mi primer chunk, empecemos por un simple paste!"

Que és un chunk?

```{r, fig.height=4}
library(ggplot2)
p <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point(aes(color = Species))
p + ggtitle("In R we trust!")
```

Que és un chunk?

```{r, fig.height=4}
library(ggplot2)
p <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point(aes(color = Species))
p + ggtitle("In R we trust!")
```

Chunk/Text results

```{r}
paste("echo TRUE, vemos el código.")
```
paste("echo TRUE, vemos el código.")
## [1] "echo TRUE, vemos el código."
```{r,echo=FALSE}
library(knitr)
paste("echo FALSE, lo usaremos casi por defecto..")
rnorm(10)
```
## Warning: package 'knitr' was built under R version 3.1.2
## [1] "echo FALSE, lo usaremos casi por defecto.."
##  [1]  0.3894842  0.5984844 -1.3152196 -0.3782137  1.1915054 -0.1064620
##  [7] -0.2153095 -1.7491474 -1.3376607 -1.1360363
```{r,echo=FALSE,results='asis'}
paste("Results as is, tal cual.")
```

[1] “Results as is, tal cual.”

cat("<h2>Html Code all night long</h2>")

Html Code all night long

```{r,echo=FALSE,results='hide'}
paste("No muestres ningún resultado.")
```

Chunk/Evaluation

Eval<-TRUE
```{r,eval=Eval}
paste(Eval)
```
paste(Eval)
## [1] "TRUE"

Chunk/Plot

```{r, echo=FALSE,fig.height=2,fig.width:3,fig.align='left',dpi=100}
library(ggplot2);library(knitr)
p <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point(aes(color = Species))
p + ggtitle("In R we trust!")
```

Chunk/Code decoration

```{all-code, ref.label=all_labels(), echo=TRUE, eval=FALSE,tidy=TRUE}
```

Chunk/Cache

Chunk/Global options

library(knitr)

opts_chunk$set(echo = FALSE)
## $eval
## [1] TRUE
## 
## $echo
## [1] FALSE
## 
## $results
## [1] "markup"
## 
## $tidy
## [1] FALSE
## 
## $tidy.opts
## NULL
## 
## $collapse
## [1] FALSE
## 
## $prompt
## [1] FALSE
## 
## $comment
## [1] "##"
## 
## $highlight
## [1] TRUE
## 
## $strip.white
## [1] TRUE
## 
## $size
## [1] "normalsize"
## 
## $background
## [1] "#F7F7F7"
## 
## $cache
## [1] FALSE
## 
## $cache.path
## [1] "Presentacio_cache/slidy/"
## 
## $cache.vars
## NULL
## 
## $cache.lazy
## [1] TRUE
## 
## $dependson
## NULL
## 
## $autodep
## [1] FALSE
## 
## $fig.keep
## [1] "high"
## 
## $fig.show
## [1] "asis"
## 
## $fig.align
## [1] "default"
## 
## $fig.path
## [1] "Presentacio_files/figure-slidy/"
## 
## $dev
## [1] "png"
## 
## $dev.args
## NULL
## 
## $dpi
## [1] 96
## 
## $fig.ext
## NULL
## 
## $fig.width
## [1] 8
## 
## $fig.height
## [1] 6
## 
## $fig.env
## [1] "figure"
## 
## $fig.cap
## NULL
## 
## $fig.scap
## NULL
## 
## $fig.lp
## [1] "fig:"
## 
## $fig.subcap
## NULL
## 
## $fig.pos
## [1] ""
## 
## $out.width
## NULL
## 
## $out.height
## NULL
## 
## $out.extra
## NULL
## 
## $fig.retina
## [1] 2
## 
## $external
## [1] TRUE
## 
## $sanitize
## [1] FALSE
## 
## $interval
## [1] 1
## 
## $aniopts
## [1] "controls,loop"
## 
## $warning
## [1] TRUE
## 
## $error
## [1] FALSE
## 
## $message
## [1] TRUE
## 
## $render
## NULL
## 
## $ref.label
## NULL
## 
## $child
## NULL
## 
## $engine
## [1] "R"
## 
## $split
## [1] FALSE
## 
## $include
## [1] TRUE
## 
## $purl
## [1] TRUE

Ejemplo: rCharts

```{r results = 'asis', comment = NA}
require(rCharts)
data(economics, package = 'ggplot2')
econ <- transform(economics, date = as.character(date))
m1 <- mPlot(x = 'date', y = c('psavert', 'uempmed'), type = 'Line',
  data = econ)
m1$set(pointSize = 0, lineWidth = 1)
m1$print('chart2', include_assets = TRUE)
```

Ejercicio 3: Define diferentes chunks

More Examples?

https://github.com/yihui/knitr-examples

Presentation Templates

Foo3

Añadir codigo html directamente

<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d2992.980538837813!2d2.1940529999999994!3d41.396229!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x12a4a2c2e2d59ceb%3A0xc4a659466688fe8d!2sitnig!5e0!3m2!1sca!2ses!4v1425493445609" width="600" height="450" frameborder="0" style="border:0"></iframe>

Añadir codigo html desde R

```{r results = 'asis', warning = FALSE}
library(dygraphs)
lungDeaths <- cbind(mdeaths, fdeaths)
dygraph(lungDeath)
```

Mejorando el aspecto de las tablas

Chunk option result = ‘asis’

http://cran.r-project.org/web/views/ReproducibleResearch.html

Ejemplo con xtable

## <!-- html table generated in R 3.1.1 by xtable 1.7-4 package -->
## <!-- Wed Mar  4 20:44:50 2015 -->
## <table border=1>
## <caption align="bottom"> 5 primeros valores de iris </caption>
## <tr> <th>  </th> <th> Sepal.Length </th> <th> Sepal.Width </th> <th> Petal.Length </th> <th> Petal.Width </th> <th> Species </th>  </tr>
##   <tr> <td align="right"> 1 </td> <td align="right"> 5.10 </td> <td align="right"> 3.50 </td> <td align="right"> 1.40 </td> <td align="right"> 0.20 </td> <td> setosa </td> </tr>
##   <tr> <td align="right"> 2 </td> <td align="right"> 4.90 </td> <td align="right"> 3.00 </td> <td align="right"> 1.40 </td> <td align="right"> 0.20 </td> <td> setosa </td> </tr>
##   <tr> <td align="right"> 3 </td> <td align="right"> 4.70 </td> <td align="right"> 3.20 </td> <td align="right"> 1.30 </td> <td align="right"> 0.20 </td> <td> setosa </td> </tr>
##   <tr> <td align="right"> 4 </td> <td align="right"> 4.60 </td> <td align="right"> 3.10 </td> <td align="right"> 1.50 </td> <td align="right"> 0.20 </td> <td> setosa </td> </tr>
##   <tr> <td align="right"> 5 </td> <td align="right"> 5.00 </td> <td align="right"> 3.60 </td> <td align="right"> 1.40 </td> <td align="right"> 0.20 </td> <td> setosa </td> </tr>
##   <tr> <td align="right"> 6 </td> <td align="right"> 5.40 </td> <td align="right"> 3.90 </td> <td align="right"> 1.70 </td> <td align="right"> 0.40 </td> <td> setosa </td> </tr>
##    </table>

Añadiendo el chunk option result = ‘asis’

5 primeros valores de iris
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.10 3.50 1.40 0.20 setosa
2 4.90 3.00 1.40 0.20 setosa
3 4.70 3.20 1.30 0.20 setosa
4 4.60 3.10 1.50 0.20 setosa
5 5.00 3.60 1.40 0.20 setosa
6 5.40 3.90 1.70 0.40 setosa

Usando knit_print

render = knit_print

library(“printr”)

https://github.com/yihui/printr

Ejemplo knit_print

##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
5.1 3.5 1.4 0.2 setosa
4.9 3.0 1.4 0.2 setosa
4.7 3.2 1.3 0.2 setosa
4.6 3.1 1.5 0.2 setosa
5.0 3.6 1.4 0.2 setosa
5.4 3.9 1.7 0.4 setosa

Añadiendo opciones de LaTeX

---
title: "Primer documento rmarkdown"
author: "Lluís Ramon"
date: "Wednesday, March 04, 2015"
output: pdf_document
header-includes:
- \usepackage{fancyhdr}
- \fancyfoot[CO,CE]{\em pàg. \thepage}
- \fancyhead[LE,LO]{\em \thetitle}
- \rfoot{\includegraphics[width = 3cm]{sct_gris}}
- \lfoot{\includegraphics[width = 3cm]{gen_gris}}
---

Usar otras templates

templates

Crear tu propia template

.Rnw/LaTeX

output_option

.Rnw/Creación Documento

output_option

output_option

Recordar, Tools / Global Options:

output_option

.Rnw/Estructuración Documento

output_option

output_option

.Rnw/Cómo funciona

output_option

.Rnw/Chunk


<>=
rnorm(10)
@

Ejercicio 4: Crear un Rnw

OR

.Rnw/Tipo output

1.
 \documentclass[12pt]{article}
2.
 \documentclass{beamer}

Más información en: http://en.wikibooks.org/wiki/LaTeX/Presentations

.Rnw/Tips

 \usepackage[utf8x]{inputenc}
 \usepackage[cp1252]{inputenc}

.Rnw vs .Rmd

Markdown or LaTeX?

output_option

.Rnw/Ejemplos Ejemplos Ejemplos

https://github.com/yihui/knitr-examples

https://github.com/yihui/knitr-examples

https://github.com/yihui/knitr-examples

https://github.com/yihui/knitr-examples

https://github.com/yihui/knitr-examples

https://github.com/yihui/knitr-examples

https://github.com/yihui/knitr-examples

https://github.com/yihui/knitr-examples

.Rnw/En caso de duda…

output_option

Thanks!